﻿using Infrastructure.Dao;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DormMS.Model;
using Infrastructure.Tool;
using DormMS.IService;
using DormMS.Model.ViewModels;
using Infrastructure.Pub;
using ServiceStack;
using DormMS.Model.SearchModels;
using Infrastructure;

namespace DormMS.Service
{
    public class UserInfoService : IUserInfoService
    {

        public CacheUserInfo GetUserInfo(int Id)
        {
            using (var _db = DbConfig.GetInstance())
            {
                _db.CurrentFilterKey = "FalseDelteJoin";

                var data = _db.Queryable<UserInfo>().JoinTable<Department>((m, n) => m.DepartmentId == n.Id).Select<UserInfo, Department, UserViewModel>((m, n) => new UserViewModel
                {
                    Id = m.Id,
                    UserName = m.UserName,
                    Password = m.Password,
                    GroupId = m.GroupId,
                    RealName = m.RealName,
                    Avatar = m.Avatar,
                    Email = m.Email,
                    Phone = m.Phone,
                    UserState = m.UserState,
                    DepartmentId = m.DepartmentId,
                    DynamicPassword = m.DynamicPassword,
                    IdCard = m.IdCard,
                    IsTeacher = m.IsTeacher,
                    Sex = m.Sex,
                    Picture = m.Picture,
                    DepartmentName = n.DepartmentName,
                    IsDeleted = m.IsDeleted,
                    AuthorityGroup = m.AuthorityGroup
                }).ToList();
               
                var user = data.FirstOrDefault(m => m.Id == Id);
                if (user == null)
                {
                    return null;
                }
                _db.CurrentFilterKey = "FalseDelte";

                var cacheuser = user.ConvertTo<CacheUserInfo>();

                var group = _db.Queryable<UserGroup>().SingleOrDefault(t => t.Id == user.GroupId);
                if (group != null && group.Id > 0)
                {
                    cacheuser.IsAdmin = group.IsAdmin;
                    cacheuser.GroupName = group.GroupName;
                }

                var userrole = _db.Queryable<UserGroupRole>().Where(t => t.UserGroupId == user.GroupId).ToList();
                if (userrole != null && userrole.Count > 0)
                {
                    var userroles = new List<UserRole>();
                    userrole.ForEach(m => userroles.Add(new UserRole { MenuRole = m.MenuId.ToString(), OperateRoles = m.OperateRoles }));
                    cacheuser.UserRoles = userroles;
                }

                var wxconfig = _db.Queryable<WxConfig>().SingleOrDefault(m => m.Id > 0);
                if (wxconfig != null)
                {
                    cacheuser.AppId = wxconfig.AppId;
                    cacheuser.AppSecret = wxconfig.AppSecret;
                }

                return cacheuser;
            }
        }
        /// <summary>
        /// 通过登录名（学号或工号）查找用户信息
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public CacheUserInfo GetUserInfo(string userName)
        {
            using (var _db = DbConfig.GetInstance())
            {
                //var user = _db.Queryable<UserInfo>().FirstOrDefault(t => t.UserName == userName);
                _db.CurrentFilterKey = "FalseDelteJoin";

                var data = _db.Queryable<UserInfo>().JoinTable<Department>((m, n) => m.DepartmentId == n.Id).Select<UserInfo, Department, UserViewModel>((m, n) => new UserViewModel
                {
                    Id = m.Id,
                    UserName = m.UserName,
                    Password = m.Password,
                    GroupId = m.GroupId,
                    RealName = m.RealName,
                    Avatar = m.Avatar,
                    Email = m.Email,
                    Phone = m.Phone,
                    UserState = m.UserState,
                    DepartmentId = m.DepartmentId,
                    DynamicPassword = m.DynamicPassword,
                    IdCard = m.IdCard,
                    IsTeacher = m.IsTeacher,
                    Sex = m.Sex,
                    Picture = m.Picture,
                    DepartmentName = n.DepartmentName,
                    IsDeleted = m.IsDeleted,
                    AuthorityGroup = m.AuthorityGroup
                }).ToList();

                var user = data.FirstOrDefault(m => m.UserName == userName);
                if (user == null)
                {
                    return null;
                }
                _db.CurrentFilterKey = "FalseDelte";

                var cacheuser = user.ConvertTo<CacheUserInfo>();

                var group = _db.Queryable<UserGroup>().SingleOrDefault(t => t.Id == user.GroupId);
                if (group != null && group.Id > 0)
                {
                    cacheuser.IsAdmin = group.IsAdmin;

                    //追加查询，新增，修改，删除的权限
                    if (group.IsAdmin == true)
                    {                        
                        cacheuser.IsAdd = true;
                        cacheuser.IsEdit = true;
                        cacheuser.IsQuery = true;
                        cacheuser.IsDel = true;
                    }
                    else
                    {
                        cacheuser.IsAdd = group.IsAdd;
                        cacheuser.IsEdit = group.IsEdit;
                        cacheuser.IsQuery = group.IsQuery;
                        cacheuser.IsDel = group.IsDel;
                    }
                    
                }

                var userrole = _db.Queryable<UserGroupRole>().Where(t => t.UserGroupId == user.GroupId).ToList();
                if (userrole != null && userrole.Count > 0)
                {
                    var userroles = new List<UserRole>();
                    userrole.ForEach(m => userroles.Add(new UserRole { MenuRole = m.MenuId.ToString(), OperateRoles = m.OperateRoles }));
                    cacheuser.UserRoles = userroles;
                }

                return cacheuser;
            }
        }

        /// <summary>
        /// 验证用户名和密码
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool CheckUserInfo(string userName, string password)
        {
            using (var _db = DbConfig.GetInstance())
            {
                var user = _db.Queryable<UserInfo>().FirstOrDefault(t => t.UserName == userName);
                if (user != null && user.Password == password)
                {
                    return true;
                }
                return false;
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="pwssword">原密码</param>
        /// <param name="newPassword">新密码</param>
        /// <returns></returns>
        public bool UpdatePassword(int userId, string pwssword, string newPassword)
        {
            using (var _db = DbConfig.GetInstance())
            {
                var user = GetUserInfo(userId);
                if (user == null)
                {
                    throw new Exception("用户不存在");
                }
                if (user.Password != pwssword)
                {
                    throw new Exception("原密码不正确");
                }

                user.Password = Generator.MD5(newPassword);

                return _db.Update<UserInfo>(user);
            }
        }

        public List<UserInfo> GetUserList(string where = "")
        {
            using (var _db = DbConfig.GetInstance())
            {
                var list = _db.Queryable<UserInfo>().Where(where).ToList();
                return list;
            }
        }

        public CacheUserInfo GetCacheUser()
        {
            string uid = Generator.GetCookie(PubConst.CookieUserKey);
            if (!uid.IsNullOrEmpty())
            {
                string uniqueKey = string.Format(PubConst.CacheUserKey, uid);
                var user = CacheManager<CacheUserInfo>.GetInstance()[uniqueKey];
                if (!(user != null && user.Id > 0)||user.GroupName.IsNullOrEmpty())
                {
                    user = GetUserInfo(uid.ObjToInt());
                    CacheManager<CacheUserInfo>.GetInstance().Add(uniqueKey, user,600);
                }
                return user;
            }

            return new CacheUserInfo();
        }

        public void SetCacheUser(int uid)
        {
            string uniqueKey = string.Format(PubConst.CacheUserKey, uid.ToString());
            var user = GetUserInfo(uid);

            CacheManager<CacheUserInfo>.GetInstance().Add(uniqueKey, user, 600);
        }

        public List<UserViewModel> GetUserList(UserSearchModel search, out int total)
        {
            using (var _db = DbConfig.GetInstance())
            {
                _db.CurrentFilterKey = "";
                Sqlable sable = _db.Sqlable().From<UserInfo>("u").Join<UserGroup>("g", "u.GroupId", "g.Id", JoinType.Left);
                sable.Where(" u.IsDeleted=0 ");
                if (!search.Keywords.IsNullOrEmpty())
                {
                    sable.Where(" (u.UserName like @userName or u.RealName like @realName or u.Phone like @phone) ");
                }

                if (search.UserGroupId > 0)
                {
                    sable.Where(" u.GroupId=@groupId ");
                }

                if (search.UserState > -1)
                {
                    sable.Where(" u.UserState=@userState ");
                }

                var pars = new { userName = "%" + search.Keywords + "%", realName = "%" + search.Keywords + "%", phone = "%" + search.Keywords + "%", groupId = search.UserGroupId, userState = search.UserState };
                total = sable.Count(pars);
                var list = sable.SelectToPageList<UserViewModel>("u.*,g.IsAdmin,g.GroupName", "u." + search.OrderByFields, search.Skip / search.Take + 1, search.Take, pars);
                
                list.ForEach(m =>
                {
                    string[] groupID = m.AuthorityGroup.Split(char.Parse(","));
                    for (int j = 1; j < groupID.Length; j++)
                    {
                        int k = Convert.ToInt32(groupID[j]);
                        var group = _db.Queryable<UserGroup>().SingleOrDefault(t => t.Id == k);

                        m.GroupName = m.GroupName + "," + group.GroupName;

                    }
                });

                return list;

            }
        }

        public Result UpdateUserPassWord(int Id, string NewPassword, int currentUserId, string OldPassword = "")
        {
            using (var Db = DbConfig.GetInstance())
            {
                var user = Db.Queryable<UserInfo>().SingleOrDefault(m => m.Id == Id);
                if (user == null || user.Id == 0)
                {
                    return Result.Failure("该用户不存在");
                }

                if (!OldPassword.IsNullOrEmpty())
                {
                    if (user.Password != Generator.MD5(OldPassword))
                    {
                        return Result.Failure("原密码不正确");
                    }
                }

                user.Password = Generator.MD5(NewPassword);
                user.EditTime = DateTime.Now;
                user.EditUserId = currentUserId;
                if (Db.Update(user))
                {
                    return Result.Success();
                }
                return Result.Failure("修改失败");
            }
        }

        public Result DelUser(int Id, int currentUserId)
        {
            using (var Db = DbConfig.GetInstance())
            {
                var user = Db.Queryable<UserInfo>().SingleOrDefault(m => m.Id == Id);
                if (user == null || user.Id == 0)
                {
                    return Result.Failure("该用户不存在");
                }
                user.IsDeleted = true;
                user.EditUserId = currentUserId;
                user.EditTime = DateTime.Now;
                if (Db.Update(user))
                {
                    return Result.Success();
                }
                return Result.Failure("操作失败");
            }
        }

        public UserInfo GetUserInfoById(int Id)
        {
            using (var Db = DbConfig.GetInstance())
            {
                return Db.Queryable<UserInfo>().SingleOrDefault(m => m.Id == Id);
            }
        }

        public Result UserEditSubmit(UserInfo user, int currentUserId)
        {
            if (user == null)
            {
                return Result.Failure("传入参数有误");
            }

            using (var Db = DbConfig.GetInstance())
            {
                var isexist = Db.Queryable<UserInfo>().Where(m => m.UserName == user.UserName && m.Id != user.Id).Count();
                if (isexist > 0)
                {
                    return Result.Failure("该用户名已存在");
                }

                if (user.Id == 0)
                {
                    user.Password = Generator.MD5(user.Password);
                    user.AddUserId = currentUserId;
                    user.DynamicPassword = "";
                    user.IdCard = "";
                    user.IsTeacher = 0;
                    user.Sex = 1;
                    Db.Insert(user);
                }
                else
                {
                    user.EditTime = DateTime.Now;
                    user.EditUserId = currentUserId;
                    user.DynamicPassword = "";
                    user.IdCard = "";
                    user.IsTeacher = 0;
                    user.Sex = 1;
                    Db.Update(user);
                }
                return Result.Success();
            }
        }

        public Result ChangeUserState(int Id, int userState, int currentUserId)
        {
            using (var Db = DbConfig.GetInstance())
            {
                var user = Db.Queryable<UserInfo>().SingleOrDefault(m => m.Id == Id);
                if (user == null || user.Id == 0)
                {
                    return Result.Failure("该用户不存在");
                }

                user.UserState = userState;
                user.EditTime = DateTime.Now;
                user.EditUserId = currentUserId;
                if (Db.Update(user))
                {
                    return Result.Success();
                }
                return Result.Failure("更新失败");
            }
        }
        /// <summary>
        /// 通系部Id找教师Id
        /// </summary>
        /// <param name="departmentID"></param>
        /// <returns></returns>
        public List<V_Teacher> GetTeacherByDepartmentID(int departmentID)
        {
            using (var db = DbConfig.GetInstance())
            {
                db.CurrentFilterKey = "";
                var data = db.Queryable<UserInfo>().JoinTable<Department>((m,s2) => m.DepartmentId == s2.Id).Where(m => m.DepartmentId == departmentID && m.IsTeacher == 1).JoinTable<Class>((m,s3) => m.ClassId == s3.Id).Select<UserInfo, Department, Class, V_Teacher>((m,s2,s3) => new V_Teacher { Id = m.Id, RealName = m.RealName, DepartmentName = s2.DepartmentName, ClassName = s3.ClassName }).ToList();
                return data;
            }
        }

        /// <summary>
        /// 通过用户中的isTeacher是否教师标记返回是否教师信息
        /// </summary>
        /// <param name="isTeacher"></param>
        /// <returns></returns>
        public List<V_Teacher> GetUserInfoByisTeacher(int isTeacher)
        {
            using (var db = DbConfig.GetInstance())
            {
                db.CurrentFilterKey = "";
                var data = db.Queryable<UserInfo>().JoinTable<Department>((m, s2) => m.DepartmentId == s2.Id).Where(m => m.IsTeacher == isTeacher).JoinTable<Class>((m, s3) => m.ClassId == s3.Id).Select<UserInfo, Department, Class, V_Teacher>((m, s2, s3) => new V_Teacher { Id = m.Id, RealName = m.RealName,DepartmentName = s2.DepartmentName,ClassName = s3.ClassName, DepartmentId = m.DepartmentId, Sex = m.Sex, UserName = m.UserName }).ToList();
                return data;
            }
        }

        public V_Student GetUserInfoByStudentNO(string StudentNO)
        {
            using (var db = DbConfig.GetInstance())
            {
                db.CurrentFilterKey = "";
                var data = db.Queryable<UserInfo>().JoinTable<Department>((m, s2) => m.DepartmentId == s2.Id).Where(m => m.IsTeacher == 0 && m.UserName == StudentNO).JoinTable<Class>((m, s3) => m.ClassId == s3.Id).Select<UserInfo, Department, Class, V_Student>((m, s2, s3) => new V_Student { Id = m.Id, RealName = m.RealName, DepartmentName = s2.DepartmentName, ClassName = s3.ClassName, DepartmentId = m.DepartmentId,Sex = m.Sex,UserName = m.UserName }).SingleOrDefault();
                return data;
            }
        }

    }
}
